package study.Handle;

import org.springframework.security.core.Authentication;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 描述:登录成功处理器(前后端分离的情况下，登录成功跳转到前端的页面)
 * @author Ychiha
 * @version 1.0
 * @date 11/1/2022 下午9:47
 */
public class MyAuthenticationSuccessHandler implements AuthenticationSuccessHandler {

    private String url;

    public MyAuthenticationSuccessHandler(String url){
        this.url = url;
    }

    @Override
    public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {

        //获取Security的User对象
        User user = (User) authentication.getPrincipal();
        //获取用户名
        System.out.println(user.getUsername());
        //获取密码(为了安全将会返回null)
        System.out.println(user.getPassword());
        //获取权限
        System.out.println(user.getAuthorities());

        //获取IP地址
        System.out.println("ip地址:"+request.getRemoteAddr());

        //接收获取到的url，作为重定向的目标
        response.sendRedirect(url);
    }

}
